# Copyright (c) 2011 Sergey K.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.


from rs.response import Response
from rs.resource import Resource
from rs.core import get_rs, has_rs


__all__ = [
    'Error',
]


class Error(Response, Exception):

    def __call__(self, target):
        from rs.core import rs_api
        @rs_api
        def error_handler(rs):
            rs.error = self.status
        ErrorManager.error_handlers.add(target)
        return error_handler(target)

    
class ErrorManager(set):

    error_handlers = set()

    def __init__(self, resources=()):
        super(ErrorManager, self).__init__(resources)
        self.handlers = dict(build_error_handler(e)
                             for e in self.error_handlers)

    def has_error_handler(self, status):
        return status in self.handlers

    def get_error_handler(self, status):
        return self.handlers.get(status)


def build_error_handler(target):
    assert has_rs(target)
    rs = get_rs(target)
    handler = Resource()
    handler.target = target
    handler.producer = rs.producer
    return rs.error, handler